package com.gexin.weixin.controller;

import com.gexin.common.AppGlobal;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.cache.RedisKeyConst;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.weixin.kit.WeXinCacheKeyConst;
import com.gexin.weixin.kit.WxAppConst;
import com.gexin.weixin.kit.WxConfigKit;
import com.jfinal.core.NotAction;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.jfinal.ApiController;

@ControllerBind(controllerKey = "/weixin/auth", viewPath = "WEB-INF/system/")
public class WexinAuthController extends ApiController {
	private static final Log log = Log.getLog(WexinAuthController.class);

	// 授权拿到用户的详细信息
	public void index() {
		String code = getPara("code");
		Integer current_id = getParaToInt("current_id", 1);
		WeixinUser fs = null;
		if (StringUtil.isNotBlank(code) && current_id != null) {
			ApiConfig config = WxConfigKit.getApiConfig(current_id);
			SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(config.getAppId(), config.getAppSecret(), code);
			if (accessToken.getErrorCode() != null && accessToken.getErrorCode() != 0) {
				log.error("获取SnsAccessToken错误：" + accessToken.getErrorMsg());
				renderJson(new ApiResponse(false, "获取SnsAccessToken错误：" + accessToken.getErrorMsg()));
				return;
			}
			ApiResult api_result = SnsApi.getUserInfo(accessToken.getAccessToken(), accessToken.getOpenid());
			if (!api_result.isSucceed()) {
				log.error("获取getUserInfo错误：" + api_result.getErrorMsg());
				renderJson(new ApiResponse(false, "获取getUserInfo错误：" + api_result.getErrorMsg()));
				return;
			}
			fs = WeixinUser.dao.paseWxUser(api_result);
			if (fs != null && StringUtil.isNotBlank(fs.getOpenid())) {
				String key = RedisKeyConst.weixinuser_key + fs.getId();// 判断缓存
				if (CacheUtils.exists(key) == false) {
					try {
						fs.setAppid(current_id);
						fs.save();
					} catch (Exception e) {
						log.info("昵称保存失败！");
						fs.setNickname("none");
						fs.save();
					}
				}
			}
		} else {
			renderJson(new ApiResponse(false, "参数错误!"));
			return;
		}

		if (isAjax()) {
			String wx_token = fs.getWxToken();
			if (StringUtil.isNotBlank(wx_token)) {
				if(!AppGlobal.dev_Mode){
					//生产坏境才删除数据
					CacheUtils.del(WeXinCacheKeyConst.wx_token + wx_token);
				}
			}
			wx_token = StringUtil.generID();
			CacheUtils.set(WeXinCacheKeyConst.wx_token + wx_token, fs, RedisKeyConst.day * 30);//缓存三十天失效
			ApiResponse resp = new ApiResponse();
			resp.setState(true);
			resp.setData(wx_token);
			resp.setMsg("获取token 成功!");
			renderJson(resp);
		} else {
			if (fs != null && fs.getId() != null) {
				setCookie(WxAppConst.Weixin_UserCookie_Id, fs.getId() + "", WxAppConst.Weixin_UserCookie_Openid_Time);
				setCookie(WxAppConst.Current_Weixin_Cookie_AppId, current_id + "", WxAppConst.Weixin_UserCookie_Openid_Time);
			}
			String url = getSessionAttr(WxAppConst.Wexin_Auth_redirect);
			if (url == null) {
				redirect("/wx/center");
			} else {
				redirect(url);
			}
		}
	}


	@NotAction
	private boolean isAjax() {
		String requtype = getRequest().getHeader("X-Requested-With");
		if (StringUtil.isNotBlank(requtype)) {
			if (requtype.equals("XMLHttpRequest")) {
				return true;
			}
		}
		return false;
	}


	// 授权只拿openid
	public void base() {
		String code = getPara("code");
		Integer current_id = getParaToInt("current_id", 1);
		if (StringUtil.isEmpty(code) == false) {
			ApiConfig config = WxConfigKit.getApiConfig(current_id);
			SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(config.getAppId(), config.getAppSecret(), code);
			if (accessToken.getErrorCode() != null && accessToken.getErrorCode() != 0) {
				log.error("获取SnsAccessToken错误：" + accessToken.getErrorMsg());
				renderText("获取SnsAccessToken错误：" + accessToken.getErrorMsg());
				return;
			}

			if (StringUtil.isBlank(accessToken.getOpenid())) {
				log.error("获取SnsAccessToken错误 getOpenid  不存在：" + accessToken.getErrorMsg());
				renderText("获取SnsAccessToken错误：getOpenid  不存在" + accessToken.getErrorMsg());
				return;
			}
			// 把账号设置到cookie 里面去
			WeixinUser user = WeixinUser.dao.cache_getUserByOpentId(accessToken.getOpenid());
			if (user == null) {
				user = new WeixinUser();
				user.setAppid(current_id);
				user.setOpenid(accessToken.getOpenid());
				user.setInfoState(1);
				user.save();
			}
			setCookie(WxAppConst.Weixin_UserCookie_Id, user.getId() + "", WxAppConst.Weixin_UserCookie_Openid_Time);
			setCookie(WxAppConst.Current_Weixin_Cookie_AppId, current_id + "", WxAppConst.Weixin_UserCookie_Openid_Time);
		} else {
			log.error("微信授权code错误!");
		}
		// 用完他删除掉
		String url = getSessionAttr(WxAppConst.Wexin_Auth_redirect);
		if (url == null) {
			log.error("获取 url 错误  ");
			redirect("/wx/center");
		} else {
			redirect(url);
		}
	}
}
